﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;

namespace LeEdu.UI.Common
{
    /// <summary>
    /// 文件上传帮助类
    /// </summary>
    public class FileUploadHelper
    {
        public static void Save(HttpRequestBase request,string folderPath,out FileInfo fileInfo)
        {
            try
            {
                fileInfo = null;
                if (request.Files.Count <= 0)
                {
                    return;
                }

                //程序根目录路径
                string appRoot = AppDomain.CurrentDomain.BaseDirectory;
                //下载目录路径
                string uploadDirectory = Path.Combine(appRoot, folderPath);//"Uploads"
                if (!Directory.Exists(uploadDirectory))
                {
                    Directory.CreateDirectory(uploadDirectory);
                }
                string fileName = string.Empty;

                int chunk = Convert.ToInt32(request["chunk"]); //当前分块
                int chunks = Convert.ToInt32(request["chunks"]);//总的分块数量

                fileName = request["name"];

                var file = request.Files[0];
                var saveFilePath = Path.Combine(uploadDirectory, fileName);

                //单块处理
                if (chunks == 1)
                {
                    if (null != file && file.ContentLength > 0)
                    {
                        file.SaveAs(saveFilePath);
                    }
                    fileInfo= new FileInfo(saveFilePath);
                }
                //多块处理
                else
                {
                    string tempFilePath = Path.Combine(uploadDirectory, "temp_" + fileName);

                    if (chunk == 0)
                    {
                        //保存第一个分块
                        file.SaveAs(tempFilePath);
                    }
                    else
                    {
                        if (file.ContentLength > 0)
                        {
                            //追加分开
                            FileStream fs = new FileStream(tempFilePath, FileMode.Append);
                            int length = file.ContentLength;
                            byte[] input = new byte[length];
                            var stream = file.InputStream;
                            stream.Read(input, 0, length);
                            fs.Write(input, 0, length);
                            stream.Close();
                            fs.Close();
                        }
                    }

                    //文件合并完处理
                    if (chunks - chunk == 1)
                    {
                        //重命名文件
                        FileInfo fi = new FileInfo(tempFilePath);
                        fi.MoveTo(saveFilePath);
                        fileInfo = new FileInfo(saveFilePath);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 判断文件格式（真实格式）
        /// http://www.cnblogs.com/babycool 
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static bool IsAllowedExtension(string filePath)
        {

            FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            BinaryReader reader = new BinaryReader(stream);
            string fileclass = "";
            // byte buffer;
            try
            {

                //buffer = reader.ReadByte();
                //fileclass = buffer.ToString();
                //buffer = reader.ReadByte();
                //fileclass += buffer.ToString();

                for (int i = 0; i < 2; i++)
                {
                    fileclass += reader.ReadByte().ToString();
                }

            }
            catch (Exception)
            {

                throw;
            }

            if (fileclass == "255216")
            {
                return true;
            }
            else
            {
                return false;
            }

            /*文件扩展名说明
             * 255216 jpg
             * 208207 doc xls ppt wps
             * 8075 docx pptx xlsx zip
             * 5150 txt
             * 8297 rar
             * 7790 exe
             * 3780 pdf      
             * 
             * 4946/104116 txt
             * 7173        gif 
             * 255216      jpg
             * 13780       png
             * 6677        bmp
             * 239187      txt,aspx,asp,sql
             * 208207      xls.doc.ppt
             * 6063        xml
             * 6033        htm,html
             * 4742        js
             * 8075        xlsx,zip,pptx,mmap,zip
             * 8297        rar   
             * 01          accdb,mdb
             * 7790        exe,dll
             * 5666        psd 
             * 255254      rdp 
             * 10056       bt种子 
             * 64101       bat 
             * 4059        sgf    
             */

        }
    }
}